import { defineStore } from 'pinia';

export const useScoreStore = defineStore('score', {
  state: () => ({
    title: '未命名',
    composer: '',
    lyricist: '',
    keySignature: 'C',
    timeSignature: '4/4',
    tempo: 120,
    bars: [],           // 小节数组
    currentBar: [],     // 当前编辑的小节
    lyrics: []          // 歌词数组
  }),
  
  actions: {
    // 添加音符到当前小节
    addNote(note) {
      // 如果是小节线，且当前小节不为空，则添加当前小节并清空
      if ((note === '|' || note === '||' || note === '∥') && this.currentBar.length > 0) {
        this.bars.push([...this.currentBar, note]);
        this.currentBar = [];
        return;
      }
      
      this.currentBar.push(note);
    },
    
    // 添加小节
    addBar() {
      if (this.currentBar.length > 0) {
        this.bars.push([...this.currentBar]);
        this.currentBar = [];
      }
    },
    
    // 删除小节
    removeBar(index) {
      this.bars.splice(index, 1);
    },
    
    // 编辑小节
    editBar(index, notes) {
      if (index >= 0 && index < this.bars.length) {
        this.bars[index] = notes;
      }
    },
    
    // 设置歌词
    setLyrics(text) {
      this.lyrics = text.split('\n').map(line => line.trim());
    },
    
    // 清空乐谱
    clearScore() {
      this.title = '未命名';
      this.composer = '';
      this.lyricist = '';
      this.bars = [];
      this.currentBar = [];
      this.lyrics = [];
    },
    
    // 导入乐谱数据
    importScore(data) {
      this.title = data.title || '未命名';
      this.composer = data.composer || '';
      this.lyricist = data.lyricist || '';
      this.keySignature = data.keySignature || 'C';
      this.timeSignature = data.timeSignature || '4/4';
      this.tempo = data.tempo || 120;
      this.bars = data.bars || [];
      this.currentBar = data.currentBar || [];
      this.lyrics = data.lyrics || [];
    },
    
    // 导出乐谱数据
    exportScore() {
      return {
        title: this.title,
        composer: this.composer,
        lyricist: this.lyricist,
        keySignature: this.keySignature,
        timeSignature: this.timeSignature,
        tempo: this.tempo,
        bars: this.bars,
        currentBar: this.currentBar,
        lyrics: this.lyrics
      };
    }
  }
});